package com.shenyue.nbtownlet.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;

import com.shenyue.nbtownlet.R;

public class ProgressWebView extends LinearLayout {

    private Context mContext;
    private Handler mHandler = new Handler();
    private ProgressBar progressBar;
    private WebView webView;
    private ScrollView parentScrollView;

    public interface OnPageChangeListener {
        void onPageFinished();

        void onReceivedTitle(String title);
    }

    private OnPageChangeListener listener;

    public ProgressWebView(Context context) {
        this(context, null);
    }

    public ProgressWebView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ProgressWebView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.mContext = context;
        initView(context);
    }

    public void setOnPageChangeListener(OnPageChangeListener listener) {
        this.listener = listener;
    }
    public void setParentScrollView(ScrollView parentScrollView) {
        this.parentScrollView = parentScrollView;
    }

    private void initView(Context context) {
        View view = View.inflate(context, R.layout.view_web_progress, this);
        progressBar = (ProgressBar) view.findViewById(R.id.progress_bar);
        webView = (WebView) view.findViewById(R.id.web_view);

        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setTextZoom(100);
        webSettings.setDefaultFontSize(14);
        // 设置WebViewClient
        webView.setWebViewClient(new WebViewClient() {
            // url拦截
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // 使用自己的WebView组件来响应Url加载事件，而不是使用默认浏览器器加载页面
                view.loadUrl(url);
                return true;
            }

            // 页面开始加载
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                progressBar.setVisibility(View.VISIBLE);
                super.onPageStarted(view, url, favicon);
            }

            // 页面加载完成
            @Override
            public void onPageFinished(WebView view, String url) {
                if (url.equals(view.getTag()))
                    return;
                view.setTag(url);
                super.onPageFinished(view, url);
                if (listener != null) {
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            listener.onPageFinished();
                        }
                    }, 32);
                }
            }

            // WebView加载的所有资源url
            @Override
            public void onLoadResource(WebView view, String url) {
                super.onLoadResource(view, url);
            }
        });

        // 设置WebChromeClient
        webView.setWebChromeClient(new WebChromeClient() {

            @Override // 处理javascript中的alert
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
                return super.onJsAlert(view, url, message, result);
            }

            @Override // 处理javascript中的confirm
            public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
                return super.onJsConfirm(view, url, message, result);
            }

            @Override // 处理javascript中的prompt
            public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, final JsPromptResult result) {
                return super.onJsPrompt(view, url, message, defaultValue, result);
            }


            @Override // 设置网页加载的进度条
            public void onProgressChanged(WebView view, int newProgress) {
                progressBar.setProgress(newProgress);
                super.onProgressChanged(view, newProgress);
            }

            @Override // 设置程序的Title
            public void onReceivedTitle(WebView view, final String title) {
                super.onReceivedTitle(view, title);
                progressBar.setVisibility(View.GONE);
                if (listener != null) {
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            listener.onReceivedTitle(title);
                        }
                    }, 32);
                }
            }
        });
    }

    public void loadUrl(final String url) {
        if (url == null)
            return;
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                webView.loadUrl(url);
            }
        }, 32);
    }

    public WebView getWebView() {
        return webView;
    }

    public void clearCache() {
        webView.clearCache(true);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                setParentScrollAble(false);//当手指触到listview的时候，让父ScrollView交出ontouch权限，也就是让父scrollview停住不能滚动
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                setParentScrollAble(true);//当手指松开时，让父ScrollView重新拿到onTouch权限
                break;
            default:
                break;

        }
        return super.onInterceptTouchEvent(ev);
    }


    /**
     * 是否把滚动事件交给父scrollview
     *
     * @param flag
     */
    private void setParentScrollAble(boolean flag) {
        if(parentScrollView == null)
            return;
        parentScrollView.requestDisallowInterceptTouchEvent(!flag);//这里的parentScrollView就是listview外面的那个scrollview
    }
}